package com.cyh.core.framework.common.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @Author: yanhang_chen
 * @Date: 2020-09-16 14:39:11
 */
public class ExeExecutor extends Thread{

    private String cmdLine;

    public static String openExe(String cmd){
        return openExe(cmd,"");
    }

    public static String openExe(String cmd,String paras){
        return openExe(cmd + " " +paras,0);
    }

    private static String openExe(String cmd,int i) {
        BufferedReader br = null;
        BufferedReader brError = null;
        String retuenStr = "";
        try {
            //执行exe  cmd可以为字符串(exe存放路径)也可为数组，调用exe时需要传入参数时，可以传数组调用(参数有顺序要求)
            Process p = Runtime.getRuntime().exec(cmd);
            String line = null;
            //获得子进程的输入流。
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            //获得子进程的错误流。
            brError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((line = br.readLine()) != null  || (line = brError.readLine()) != null) {
                //输出exe输出的信息以及错误信息
                retuenStr += line +"\n";
                System.out.println(line);
            }
            return retuenStr;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void openExeInBackGround(String cmd){
        openExeInBackGround(cmd,"");
    }

    public static void openExeInBackGround(String cmd,String paras){
        ExeExecutor executor = new ExeExecutor();
        executor.cmdLine = cmd + " " + paras;
        executor.start();
        System.out.println(TimeUtil.getNow()+" Exe is executed !");
    }

    @Override
    public void run() {
        if(cmdLine!= null) {
            openExe(cmdLine);
        }
    }
}
